<template>
    <transition name="el-zoom-in-center">
        <div class="SHZY-preview-main">
            <div class="SHZY-common-page-header">
                <el-page-header @back="goBack" content="报工" />
                <div class="options">
                    <el-button type="primary" @click="dataFormSubmit()" :loading="btnLoading">确 定</el-button>
                    <el-button @click="goBack">取 消</el-button>
                </div>
            </div>
            <div :style="{ margin: '0 auto', width: '100%' }">
                <el-row :gutter="15" class=" main">
                    <el-form :disabled="true" ref="elForm" :model="dataForm" size="small" label-width="110px"
                        label-position="right">
                        <el-col :span="24">
                            <el-form-item label="工单号" prop="code">
                                <el-input v-model='dataForm.code' placeholder='请输入' clearable required
                                    :style='{ "width": "100%" }'>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="工单类型" prop="type">
                                <el-select v-model='dataForm.type' placeholder='请选择' clearable required
                                    :style='{ "width": "100%" }'>
                                    <el-option v-for="(item, index) in workOrderTypeData" :key="index"
                                        :label="item.fullName" :value="item.enCode"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="物料ID" prop="materialId">
                                <SHZY-select :list="materialData" v-model:bindValue="dataForm.materialId"
                                    :style='{ "width": "100%" }' label="name" value="id" placeholder="请选择物料" isConcat
                                    concatSymbol=" / ">
                                </SHZY-select>
                            </el-form-item>
                        </el-col>
                        <el-collapse-transition>
                            <div v-if="isShow">
                                <el-col :span="24">
                                    <el-form-item label="数量" prop="qty">
                                        <el-input v-model='dataForm.qty' placeholder='请输入' clearable required
                                            :style='{ "width": "100%" }'>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="单位" prop="unit">
                                        <el-select v-model='dataForm.unit' placeholder='请选择' clearable
                                            :style='{ "width": "100%" }'>
                                            <el-option v-for="(item, index) in unitData" :key="index" :label="item.fullName"
                                                :value="item.enCode"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="计划开始时间" prop="planStartTime">
                                        <el-date-picker v-model='dataForm.planStartTime' placeholder='请选择' clearable
                                            required :style='{ "width": "100%" }' type='datetime'
                                            format='yyyy-MM-dd HH:mm:ss' value-format='timestamp'>
                                        </el-date-picker>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="计划完成时间" prop="planEndTime">
                                        <el-date-picker v-model='dataForm.planEndTime' placeholder='请选择' clearable required
                                            :style='{ "width": "100%" }' type='datetime' format='yyyy-MM-dd HH:mm:ss'
                                            value-format='timestamp'>
                                        </el-date-picker>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                    <el-form-item label="备注" prop="remark">
                                        <el-input v-model='dataForm.remark' placeholder='请输入' show-word-limit
                                            :style='{ "width": "100%" }' type='textarea'
                                            :autosize='{ "minRows": 4, "maxRows": 4 }'>
                                        </el-input>
                                    </el-form-item>
                                </el-col>
                            </div>
                        </el-collapse-transition>
                    </el-form>
                    <el-form ref="elForm1" :model="reportForm" size="small" label-width="110px" label-position="right"
                        :rules="rules">
                        <el-col :span="24">
                            <el-divider>
                                <el-button type="text" icon="el-icon-arrow-down" @click="isShow = true"
                                    v-if="!isShow">展开</el-button>
                                <el-button type="text" icon="el-icon-arrow-up" @click="isShow = false" v-else>收起</el-button>
                            </el-divider>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="报工类型" prop="status">
                                <el-radio-group v-model='reportForm.status' size='small' @input="reportForm.ngQty = 0">
                                    <el-radio-button v-for="(item, index) in statusData" :key="index"
                                        :label="item.enCode">{{
                                            item.fullName }}</el-radio-button>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="作业人员" prop="operatorId">
                                <user-select v-model="reportForm.operatorId" placeholder="作业人员" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="报工数量" prop="qty">
                                <el-input v-model='reportForm.qty' placeholder='请输入' clearable required
                                    :style='{ "width": "100%" }'>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="不合格数量" prop="ngQty">
                                <el-input v-model='reportForm.ngQty' placeholder='请输入' clearable required
                                    :disabled="reportForm.status == 'OK'" :style='{ "width": "100%" }'>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="实际开始时间" prop="actualStartTime">
                                <el-date-picker v-model='reportForm.actualStartTime' placeholder='请选择' clearable required
                                    :style='{ "width": "100%" }' type='datetime' format='yyyy-MM-dd HH:mm:ss'
                                    value-format='timestamp' @change="getWorkHours">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="实际完成时间" prop="actualEndTime">
                                <el-date-picker v-model='reportForm.actualEndTime' placeholder='请选择' clearable required
                                    :style='{ "width": "100%" }' type='datetime' format='yyyy-MM-dd HH:mm:ss'
                                    value-format='timestamp' @change="getWorkHours">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="工时" prop="workHours">
                                <el-input v-model='reportForm.workHours' placeholder='请输入' clearable required
                                    :style='{ "width": "100%" }'>
                                    <template slot="append">分钟</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model='reportForm.remark' placeholder='请输入' show-word-limit
                                    :style='{ "width": "100%" }' type='textarea' :autosize='{ "minRows": 4, "maxRows": 4 }'  maxlength='500'>
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-form>
                </el-row>
            </div>
        </div>
    </transition>
</template>
<script>
import { mapGetters } from "vuex"
import { getWorkorderInfo, createWorkReport } from '@/api/q1/business/workOrder'
import { getMaterialAll } from '@/api/q1/basedata/material';
export default {
    components: {},
    props: [],
    data() {
        const qtyValidator = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error("请输入报工数量"));
            } else {
                var _reg = /^\d+$/
                if (!_reg.test(value)) {
                    callback(new Error("请输入数字"));
                } else {
                    if (parseInt(this.reportForm.qty) > parseInt(this.dataForm.qty)) {
                        callback(new Error("报工数量不能大于工单数量"));
                    } else {
                        callback();
                    }
                }
            }
        };
        const ngQtyValidator = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error("请输入不合格数量"));
            } else {
                var _reg = /^\d+$/
                if (!_reg.test(value)) {
                    callback(new Error("请输入数字"));
                } else {
                    if (parseInt(this.reportForm.ngQty) > parseInt(this.dataForm.qty)) {
                        callback(new Error("不合格数量不能大于工单数量"));
                    } else {
                        callback();
                    }
                }
            }
        };
        const actualStartTimeValidator = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error("请选择实际开始时间"));
            } else {
                let date1 = new Date(this.dataForm.actualStartTime);
                let date2 = new Date(this.dataForm.actualEndTime);
                if (date1.getTime() > date2.getTime()) {
                    callback(new Error("实际开始时间必须小于或等于实际完成时间"));
                } else {
                    callback();
                }
            }
        };
        const actualEndTimeValidator = (rule, value, callback) => {
            if (value.length == 0) {
                callback(new Error("请选择实际完成时间"));
            } else {
                let date1 = new Date(this.dataForm.actualStartTime);
                let date2 = new Date(this.dataForm.actualEndTime);
                console.log(date1.getTime(), date2.getTime())
                if (date1.getTime() > date2.getTime()) {
                    callback(new Error("实际完成时间必须大于或等于实际开始时间"));
                } else {
                    callback();
                }
            }
        };
        return {
            btnLoading: false,
            loading: false,
            visible: false,
            isShow: false,
            dataForm: {
                id: "",
                code: "",
                type: "",
                materialId: "",
                qty: "",
                unit: "",
                planStartTime: "",
                planEndTime: "",
                remark: "",
                status: 0,
            },
            reportForm: {
                workOrderId: "",
                status: "OK",
                operatorId: "",
                qty: "",
                ngQty: 0,
                actualStartTime: "",
                actualEndTime: "",
                workHours: "",
                remark: "",
            },
            rules: {
                operatorId: [{ required: true, message: '请输入工单号', trigger: '"blur"' }],
                qty: [{ required: true, validator: qtyValidator, trigger: '"blur"' }],
                ngQty: [{ required: true, validator: ngQtyValidator, trigger: '"blur"' }],
                actualStartTime: [{ required: true, validator: actualStartTimeValidator, trigger: '"blur"' }],
                actualEndTime: [{ required: true, validator: actualEndTimeValidator, trigger: '"blur"' }],
                workHours: [
                    { required: true, message: '请输入工时', trigger: '"blur"' },
                    { pattern: /^\d+$/, message: '请输入正确的数字', trigger: '"blur"' }
                ],
            },
            workOrderTypeData: [],
            materialData: [],
            unitData: [],
            statusData: [{ 'fullName': "合格", 'enCode': "OK" }, { 'fullName': "不合格", 'enCode': "NG" }],
        }
    },
    computed: {
        ...mapGetters(['userInfo'])
    },
    watch: {},
    created() {
        this.getDictionaryData()
    },
    mounted() {
    },
    methods: {
        getDictionaryData() {
            this.$store.dispatch('base/getDictionaryData', { sort: 'workOrderType' }).then((res) => {
                this.workOrderTypeData = res
            })
            this.$store.dispatch('base/getDictionaryData', { sort: 'MaterialUnit' }).then((res) => {
                this.unitData = res
            })
        },
        goBack() {
            this.$emit('refresh')
        },
        init(id) {
            this.dataForm.id = id || 0;
            this.reportForm.workOrderId = id
            this.visible = true;
            this.$nextTick(() => {
                this.$refs['elForm'].resetFields();
                getMaterialAll().then(res => {
                    this.materialData = res.data.list;
                });

                this.reportForm.operatorId = this.userInfo.userId

                if (this.dataForm.id) {
                    getWorkorderInfo(this.dataForm.id).then(res => {
                        this.dataForm = res.data;
                    })
                }
            });
        },
        getWorkHours() {
            if (this.reportForm.actualStartTime != "" && this.reportForm.actualEndTime != "") {
                const start = new Date(this.reportForm.actualStartTime);
                const end = new Date(this.reportForm.actualEndTime);
                const diff = Math.abs(end - start)
                this.reportForm.workHours = Math.floor(diff / 1000 / 60)
            }
        },
        dataFormSubmit() {
            this.$refs['elForm1'].validate((valid) => {
                if (valid) {
                    this.btnLoading = true;
                    createWorkReport(this.reportForm).then((res) => {
                        this.btnLoading = false;
                        this.$message({
                            message: res.msg,
                            type: 'success',
                            duration: 1000,
                            onClose: () => {
                                this.visible = false,
                                    this.$emit('refresh', true)
                            }
                        })
                    }).catch((res) => {
                        this.btnLoading = false;
                    })

                }
            })
        }
    }
}
</script>
